<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>开关灯</title>
    <style>
        body {
            background-color: #000;
            transition: all 0.8s;
        }

        .switch {
            font-size: 17px;
            position: relative;
            display: inline-block;
            width: 3.5em;
            height: 2em;
        }

        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .slider {
            --background: #28096b;
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: var(--background);
            transition: .5s;
            border-radius: 30px;
        }

        .slider:before {
            position: absolute;
            content: "";
            height: 1.4em;
            width: 1.4em;
            border-radius: 50%;
            left: 10%;
            bottom: 15%;
            box-shadow: inset 8px -4px 0px 0px #fff000;
            background: var(--background);
            transition: .5s;
        }

        input:checked+.slider {
            background-color: #522ba7;
        }

        input:checked+.slider:before {
            transform: translateX(100%);
            box-shadow: inset 15px -4px 0px 15px #fff000;
        }

        .open {
            background-color: #000;
        }

        .close {
            background-color: #fff;
        }
    </style>
</head>

<body class="b">
    <label class="switch">
        <input type="checkbox">
        <span class="slider"></span>
    </label>

    <script>
        // 获取标签元素
        const slider = document.querySelector('.slider');
        // 声明初始值变量 使用改变变量来区别点击事件
        let sm = 0;
        slider.addEventListener('click', e => {
            // 当变量等于0时，给body添加close类名
            if (sm == 0) {
                document.body.classList.toggle('close');
                sm = 1;
            };
            // 当变量等于1时，给body添加open类名
            if (sm == 1) {
                document.body.classList.toggle('open')
                sm = 0;
            };
        });


    </script>
</body>

</html>